<template>
    <a-modal :width="'99%'" :visible="visible" :confirmLoading="confirmLoading" @ok="handleSubmit" :maskClosable="false"
        :okButtonProps="{ props: { disabled: disableSubmit } }" @cancel="handleCancel" cancelText="关闭"
        style="top: 20px">
        <template #title>
            <a-space align="center" :size="100">
                <p>跟单员审核-{{ (model.orderType == 1 ? '特殊订单' : '普通订单') }}</p>
                <div>
                    <a-popconfirm title="确定取消吗?" v-if="model.status == 0" placement="topLeft" v-has="'order:cancel'"
                        @confirm="() => handleCancelOrder()">
                        <a-button size="small" type="danger" :loading="loadingC" ghost>取消订单</a-button>
                    </a-popconfirm>

                    <a-popconfirm title="确定删除吗?" placement="topLeft" v-if="[0, 4, 8].includes(model.status)"
                        v-has="'order:delete'" @confirm="() => handleRepeal()">
                        <a-button size="small" type="danger" :loading="loadingD" ghost style="margin-left: 15px">删除订单</a-button>
                    </a-popconfirm>
                    <a-button size="small" style="margin-left: 15px" @click="$emit('handleTrace', model)">订单跟踪</a-button>
                </div>
      </a-space>
            
        </template>
        <a-spin :spinning="confirmLoading">
            <a-row :gutter="24" style="margin-bottom: 10px;">
                <!-- <a-col :md="8" :sm="24">
                    <a-form :form="form" labelAlign="left" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <a-form-item label="请选择" style="margin-bottom: 10px;">
                            <j-dict-select-tag v-decorator="['orderFlag', validatorRules.status]"
                                @change="handleWarehouseFlag" :type="'radioButton'" :triggerChange="true"
                                dictCode="orderAdminReview_status" />
                        </a-form-item>
                        <a-form-item v-if="model.orderFlag != 1" label="拒绝备注" style="margin-bottom: 10px;">
                            <a-textarea :rows="1" placeholder="请输入拒绝备注" v-decorator="['note', validatorRules.note]" />
                        </a-form-item>
                    </a-form>
                </a-col> -->
                <a-col :md="16" :sm="24">
                    <a-table :columns="discountColumns" style="width: 800px" :data-source="[discountData]" size="small"
                        rowKey="orderId" bordered :pagination="false">
                        <template slot="remainAmount" slot-scope="text">
                            {{ text }}
                        </template>
                    </a-table>
                </a-col>
            </a-row>
            <h3 v-if="skuStockWaring.length > 0" style="color: red; font-weight: bold;font-size: 16px; ">存在商品库存不足</h3>
            <a-table size="small" ref="table" id="orderEditTable" :columns="goodsColumns" :dataSource="goodsData" :scroll="{ x: 1000 }" 
                bordered class="minTable" rowKey="productSkuCode" :pagination="false" :loading="loading"  style="font-size: 12px;">

                <!-- <div slot="realAmount" slot-scope="realAmount, row">
                    <a-input-number :value="realAmount" :min="0" @change="onChangeAmount($event, row)"
                        :precision="2" :disabled="row.orderProductType == 1" />
                </div> -->
                <!-- 总数 -->
                <div slot="sendProQty" slot-scope="sendProQty, row" class="canDeal">
                    <a-input-number :precision="0" :value="sendProQty" :min="0" style="width: 70px"
                        @change="onChangeQuantity($event, row)" />
                </div>
                <!-- 箱数 -->
                <div slot="sendQty" slot-scope="sendQty, row" class="canDeal">
                    <a-input-number :precision="3" :value="sendQty" :min="0" style="width: 70px"
                        @change="onChangeBox($event, row)" />
                </div>
                <template slot="totalProductAmount" slot-scope="totalProductAmount">
                    <p>{{ totalProductAmount }}</p>
                </template>
                <div slot="needPayAmount" slot-scope="needPayAmount,row">{{ needPayAmount }}</div>

                <div slot="stock_warning" slot-scope="stock_warning, row">
                    <a-space>
                        <div :style="{ 'color': row.sendProQty > row.stockUnit ? 'red' : '#333' }">
                            {{ stock_warning }}
                        </div>
                    </a-space>
                </div>

                <div slot="minUnitPrice" slot-scope="minUnitPrice, row" :class="{'canDeal':model.orderType == 1}">
                    <div v-if="model.orderType == 1">
                        <a-input-number :precision="2" :value="minUnitPrice" :min="0" style="width: 60px"
                            @change="setPrice($event, row)"/>
                    </div>
                    <div v-else>{{ minUnitPrice }}</div>

                </div>

                <template slot="customTitleG" slot-scope="text,value">
                    <table-head title="货物优惠" @clickHandle="setRate('productDiscountRate')" />
                </template>
                <template slot="customTitleS" slot-scope="text,value">
                    <table-head title="促销优惠" @clickHandle="setRate('promotionDiscountRate')" />
                </template>
                <template slot="customTitleM" slot-scope="text,value">
                    <table-head title="任务完成" @clickHandle="setRate('missionDiscountRate')" />
                </template>
                <template slot="customTitleA" slot-scope="text,value">
                    <table-head title="调价补差" @clickHandle="setRate('adjustDiscountRate')" />
                </template>



                <!-- 货物优惠 -->
                <div slot="productDiscountRate" slot-scope="productDiscountRate, row" :class="{'canDeal':!disableProductDiscountInput}">
                    <a-input-number :precision="2" :value="productDiscountRate" :min="0" style="width: 70px"
                        :disabled="disableProductDiscountInput" @change="onChangeProductRate($event, row)" />
                </div>
                <div slot="productDiscountAmount" slot-scope="productDiscountAmount, row" :class="{'canDeal':!disableProductDiscountInput}">
                    <a-input-number :precision="2" :value="productDiscountAmount" :min="0" style="width: 80px"
                        :disabled="disableProductDiscountInput" @change="onChangeProductAmount($event, row)" />
                </div>

                <!-- 促销费用 -->
                <div slot="promotionDiscountRate" slot-scope="promotionDiscountRate, row" :class="{'canDeal':!disablePromotionDiscountInput}">
                    <a-input-number :precision="2" :value="promotionDiscountRate" :min="0" style="width: 70px"
                        :disabled="disablePromotionDiscountInput" @change="onChangePromotionRate($event, row)" />
                </div>
                <div slot="promotionDiscountAmount" slot-scope="promotionDiscountAmount, row" :class="{'canDeal':!disablePromotionDiscountInput}">
                    <a-input-number :precision="2" :value="promotionDiscountAmount" :min="0" style="width: 80px"
                        :disabled="disablePromotionDiscountInput" @change="onChangePromotionAmount($event, row)" />
                </div>
                <!-- 任务完成 -->
                <div slot="missionDiscountRate" slot-scope="missionDiscountRate, row" :class="{'canDeal':!disableMissionDiscountInput}">
                    <a-input-number :precision="2" :value="missionDiscountRate" :min="0" style="width: 70px"
                        :disabled="disableMissionDiscountInput" @change="onChangeMissionRate($event, row)" />
                </div>
                <div slot="missionDiscountAmount" slot-scope="missionDiscountAmount, row" :class="{'canDeal':!disableMissionDiscountInput}">
                    <a-input-number :precision="2" :value="missionDiscountAmount" :min="0" style="width: 80px"
                        :disabled="disableMissionDiscountInput" @change="onChangeMissionAmount($event, row)" />
                </div>

                <!-- 调价补差 -->
                <div slot="adjustDiscountRate" slot-scope="adjustDiscountRate, row" :class="{'canDeal':!disableAdjustDiscountInput}">
                    <a-input-number :precision="2" :value="adjustDiscountRate" :min="0" style="width: 70px"
                        :disabled="disableAdjustDiscountInput" @change="onChangeAdjustRate($event, row)" />
                </div>
                <div slot="adjustDiscountAmount" slot-scope="adjustDiscountAmount, row" :class="{'canDeal':!disableAdjustDiscountInput}">
                    <a-input-number :precision="2" :value="adjustDiscountAmount" :min="0" style="width: 80px"
                        :disabled="disableAdjustDiscountInput" @change="onChangeAdjustAmount($event, row)" />
                </div>
                <template slot="footer">
                    <a-table size="small" :columns="goodsColumns" :showHeader="false" :dataSource="footerDataSource"
                        :scroll="{ x: 1000 }" rowKey="index" class="footerTable" :pagination="false"
                        style="font-size: 12px;">
                        <div slot="sendProQty" slot-scope="sendProQty,row">{{ sendProQty }}</div>
                        <div slot="sendQty" slot-scope="sendQty,row">{{ sendQty }}</div>
                        <div slot="totalProductAmount" slot-scope="totalProductAmount">
                            <p>{{ totalProductAmount }}</p>
                        </div>
                        <div slot="needPayAmount" slot-scope="needPayAmount">
                            <p :class="{ 'red': needPayAmount > discountData.balance }">{{ needPayAmount }}</p>
                        </div>

                        <div slot="stock_warning"></div>
                        <div slot="productDiscountRate"></div>
                        <div slot="productDiscountAmount" slot-scope="productDiscountAmount">
                            <p :class="{ 'red': productDiscountAmount > discountData.productRemainAmount }">{{
                                productDiscountAmount }}</p>
                        </div>
                        <div slot="promotionDiscountRate"></div>
                        <div slot="promotionDiscountAmount" slot-scope="promotionDiscountAmount">
                            <p :class="{ 'red': promotionDiscountAmount > discountData.promotionRemainAmount }">{{
                                promotionDiscountAmount }}</p>
                        </div>
                        <div slot="missionDiscountRate"></div>
                        <div slot="missionDiscountAmount" slot-scope="missionDiscountAmount">
                            <p :class="{ 'red': missionDiscountAmount > discountData.missionRemainAmount }">{{
                                missionDiscountAmount }}</p>
                        </div>
                        <div slot="adjustDiscountRate"></div>
                        <div slot="adjustDiscountAmount" slot-scope="adjustDiscountAmount">
                            <p :class="{ 'red': adjustDiscountAmount > discountData.adjustRemainAmount }">{{
                                adjustDiscountAmount }}</p>
                        </div>
                    </a-table>
                </template>

            </a-table>
        </a-spin>
    </a-modal>
</template>
<!-- 
    每次数量变化会重新计算4大折扣，固定折扣额
    每次折扣输入变化会校验最大可输入数值，和固定折扣额
 -->
<script>
import pick from "lodash.pick";
import { httpAction, getAction } from "@/api/manage";
import { fixedTwo ,fixedThree} from '@/utils/util';
import tableHead from '@/components/customView/tableHead.vue'

export default {
    name: "OmsOrderEditApplyModal",

    data() {
        return {
            visible: false,
            confirmLoading: false,
            isChanged: false,
            creditLimit: 0,
            remainCreditLimit: 0,
            skuStockWaring: [],
            usedCreditLimit: 0,
            disableMissionDiscountInput: false, // 是否允许编辑折扣
            disableAdjustDiscountInput: false,
            disableProductDiscountInput: false,
            disablePromotionDiscountInput: false,
            note: "",
            validatorRules: {
                status: { rules: [{ required: true, message: "请选择状态!" }] },
                note: { rules: [{ required: true, message: "请输入拒绝原因!" }] },
            },
            model: {},
            disableSubmit: false,
            discountData:
            {
                orderNo: 1,
                balance: 0,
                productRemainAmount: 0,
                promotionRemainAmount: 0,
                missionRemainAmount: 0,
                adjustRemainAmount: 0,
                productRemainAmount_total: 0,
                promotionRemainAmount_total: 0,
                missionRemainAmount_total: 0,
                adjustRemainAmount_total: 0,
            },
            discountColumns: [
                {
                    title: '订单号',
                    dataIndex: 'orderNo',
                    key: 'orderNo',
                    align: 'center'
                },
                {
                    title: '可用余额',
                    dataIndex: 'balance',
                    align: 'center',
                },
                {
                    title: "货物优惠剩余额度",
                    align: 'center',
                    dataIndex: "productRemainAmount",
                    scopedSlots: { customRender: "remainAmount" },
                },
                {
                    title: "促销费用剩余额度",
                    align: 'center',
                    dataIndex: "promotionRemainAmount",
                    scopedSlots: { customRender: "remainAmount" },
                },
                {
                    title: '任务完成剩余额度',
                    align: 'center',
                    dataIndex: 'missionRemainAmount',
                    scopedSlots: { customRender: "remainAmount" },

                },
                {
                    title: "调价补差剩余额度",
                    align: "center",
                    dataIndex: "adjustRemainAmount",
                    scopedSlots: { customRender: "remainAmount" },

                },
            ],
            goodsColumns: [
                {
                    title: '序号',
                    dataIndex: '',
                    key: 'rowIndex',
                    fixed: 'left',
                    width: 36,
                    align: 'center',
                    customRender: (t, r, index) => {
                        return t.id == 'heji' ? '-' : (Number(index) + 1)
                    }
                },
                {
                    title: "物料编码",
                    width: 100,
                    key: "productSkuCode",
                    fixed: 'left',
                    align: 'center',
                    dataIndex: "productSkuCode",
                },
                {
                    title: "物料名称",
                    key: "productName",
                    width: 120,
                    align: 'center',
                    fixed: 'left',
                    dataIndex: "productName",
                },
                // {
                //     title: '箱规',
                //     key: 'boxUnit',
                //     align: "center",
                //     width: 70,
                //     dataIndex: 'boxUnit'
                // },
                {
                    title: "单价",
                    align: "center",
                    key: "minUnitPrice",
                    width: 66,
                    dataIndex: "minUnitPrice",
                    scopedSlots: { customRender: "minUnitPrice" },
                },
                {
                    title: "箱价",
                    align: "center",
                    key: "productPrice",
                    width: 66,
                    dataIndex: "productPrice",
                },
                {
                    title: "需求数量",
                    align: "center",
                    key: "minUnitQuantity",
                    width: 66,
                    dataIndex: "minUnitQuantity",
                },
                {
                    title: "需求箱数",
                    align: "center",
                    key: "boxNum",
                    width: 66,
                    dataIndex: "boxNum",
                },
                {
                    title: "可用库存\n" + "(只)",
                    key: "stockUnit",
                    align: "center",
                    width: 66,
                    // dataIndex: "stockUnit",
                    dataIndex: "stock_warning",
                    scopedSlots: { customRender: "stock_warning" },
                },
                {
                    title: "可用库存\n" + "(箱)",
                    key: "stock",
                    align: "center",
                    width: 66,
                    dataIndex: "stock",
                },
                {
                    title: `分配数量\n(只)`,
                    align: "center",
                    width: 80,
                    dataIndex: "sendProQty",
                    scopedSlots: { customRender: "sendProQty" },
                },
                {
                    title: "分配箱数",
                    dataIndex: "sendQty",
                    width: 80,
                    align: "center",
                    scopedSlots: { customRender: "sendQty" },
                },
                {
                    title: "总金额",
                    align: "center",
                    key: "totalProductAmount",
                    width: 70,
                    dataIndex: "totalProductAmount",
                    scopedSlots: { customRender: "totalProductAmount" },
                },
                {
                    title: "优惠金额",
                    align: "center",
                    key: "discountAmount",
                    width: 70,
                    dataIndex: "discountAmount",
                },
                // {
                //     title: "可优惠金额",
                //     align: "center",
                //     key: "maxDiscountAmount",
                //     width: 70,
                //     dataIndex: "maxDiscountAmount",
                // },

                {
                    title: "应付金额",
                    align: "center",
                    key: "needPayAmount",
                    width: 70,
                    dataIndex: "needPayAmount",
                    scopedSlots: { customRender: "needPayAmount" },
                },

                {
                    align: "center",
                    dataIndex: "productDiscountRate",
                    width: 80,
                    scopedSlots: {
                        customRender: "productDiscountRate",
                        title: 'customTitleG'
                    },
                },
                {
                    title: "货物优惠\n" +
                        "折扣额",
                    width: 100,
                    align: "center",
                    dataIndex: "productDiscountAmount",
                    scopedSlots: { customRender: "productDiscountAmount" },
                },
                {

                    dataIndex: "promotionDiscountRate",
                    align: "center",
                    width: 80,
                    scopedSlots: { customRender: "promotionDiscountRate", title: 'customTitleS' },
                },
                {
                    title: "促销费用\n" +
                        "折扣额",
                    width: 100,
                    align: "center",
                    dataIndex: "promotionDiscountAmount",
                    scopedSlots: { customRender: "promotionDiscountAmount" },
                },
                {

                    dataIndex: "missionDiscountRate",
                    align: "center",
                    width: 80,
                    scopedSlots: { customRender: "missionDiscountRate", title: 'customTitleM' },
                },
                {
                    title: "任务完成\n" +
                        "折扣额",
                    width: 100,
                    align: "center",
                    dataIndex: "missionDiscountAmount",
                    scopedSlots: { customRender: "missionDiscountAmount" },
                },
                {
                    dataIndex: "adjustDiscountRate",
                    width: 80,
                    align: "center",
                    scopedSlots: { customRender: "adjustDiscountRate", title: 'customTitleA' },
                },
                {
                    title: "调价补差\n" +
                        "折扣额",
                    width: 100,
                    align: "center",
                    dataIndex: "adjustDiscountAmount",
                    scopedSlots: { customRender: "adjustDiscountAmount" },

                },
                {
                    title: "产品固定\n" +
                        "折扣率%",
                    align: "center",
                    key: "fixedDiscountRate",
                    width: 70,
                    dataIndex: "fixedDiscountRate",
                },
                {
                    title: "产品固定\n" +
                        "折扣额",
                    align: "center",
                    width: 70,
                    dataIndex: "fixedDiscountAmount",
                },
            ],
            goodsData: [],

            labelCol: {
                xs: { span: 8 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 12 },
                sm: { span: 10 },
            },
            form: undefined,
            url: {
                approve: "/oms/omsOrder/orderApprove",
                storeInfo: "stm/stmStoreInfo/storeInfo",
                omsOrderItem: {
                    list: "/oms/omsOrder/queryOmsOrderItemByMainId",
                },
                cancel: '/oms/omsOrder/cancel',
                repeal: '/oms/omsOrder/remove',
            },
            loading: false,
            maxDiscountRate: 90,// 折扣占比最大可输入百分比，根据订单设置
            loadingD:false,
            loadingC:false,
        };
    },
    computed: {
        // 合计
        footerDataSource() {
            let minUnitQuantity = 0, boxNum = 0, sendProQty = 0, sendQty = 0, totalProductAmount = 0, discountAmount = 0,
                needPayAmount = 0, fixedDiscountAmount = 0, productDiscountAmount = 0,
                promotionDiscountAmount = 0, missionDiscountAmount = 0, adjustDiscountAmount = 0;
            this.goodsData.forEach(x => {
                minUnitQuantity += x.minUnitQuantity;
                boxNum += x.boxNum;
                sendProQty += x.sendProQty;
                sendQty += x.sendQty;
                totalProductAmount += Number(x.totalProductAmount);
                discountAmount += Number(x.discountAmount);
                needPayAmount += Number(x.needPayAmount);
                fixedDiscountAmount += Number(x.fixedDiscountAmount);
                productDiscountAmount += Number(x.productDiscountAmount);
                promotionDiscountAmount += Number(x.promotionDiscountAmount);
                missionDiscountAmount += Number(x.missionDiscountAmount);
                adjustDiscountAmount += Number(x.adjustDiscountAmount);
            })
            return [{
                id: 'heji',
                productSkuCode:`合计${this.goodsData.length}行`,
                minUnitQuantity,
                boxNum: fixedThree(boxNum),
                sendProQty,
                sendQty: fixedThree(sendQty),
                totalProductAmount: fixedTwo(totalProductAmount),
                discountAmount: fixedTwo(discountAmount),
                needPayAmount: fixedTwo(needPayAmount),
                fixedDiscountAmount: fixedTwo(fixedDiscountAmount),
                productDiscountAmount: fixedTwo(productDiscountAmount),
                promotionDiscountAmount: fixedTwo(promotionDiscountAmount),
                missionDiscountAmount: fixedTwo(missionDiscountAmount),
                adjustDiscountAmount: fixedTwo(adjustDiscountAmount)
            }]
        }
    },
    methods: {
        show(record, dictCodeParm) {
            this.skuStockWaring = [];
            this.visible = true;
            console.log(record)
            this.model = Object.assign({}, record);
            this.form = this.$form.createForm(this);
            this.$nextTick(() => {
                this.model.orderFlag = 1;
                this.form.setFieldsValue(pick(this.model, "productSn", "orderFlag", "note"));
            });
            this.goodsData = [];
            if (this.model.id) {
                this.loadGoodsData();
                this.getStoreInfo(record.storeId);
            }
        },
        /**
         * 获取货物详情,重新计算箱数
         * minUnitQuantity最小单位数量
         * productQuantity箱数 转化为 向下取整 
         * sendQty  
         * fourMaxRate: 4大折扣最大和
         * maxDiscountAmount:4最大可输入折扣额 = 总金额 * （maxDiscountRate - 固定折扣率 ）
         * 固定折扣额 = （总价 - (货物优惠折扣/任务完成折扣/促销费用折扣/调价补差折扣）* 固定折扣率 
         * */
        loadGoodsData() {
            var params = { id: this.model.id };
            this.loading = true;
            getAction(this.url.omsOrderItem.list, params).then((res) => {
                if (res.success) {
                    this.maxDiscountRate = res.result[0].maxDiscount
                    this.goodsData = res.result.map((x) => {
                        let boxNum = fixedThree(x.minUnitQuantity / x.productSkuSpec),
                            fourMaxRate = this.maxDiscountRate - x.fixedDiscountRate,
                            maxDiscountAmount = fixedTwo(x.totalProductAmount * fourMaxRate / 100);
                        let sendQty = fixedThree(x.sendProQty / x.productSkuSpec);
                        return {
                            ...x,
                            fourMaxRate,
                            needPayAmount: x.totalRealAmount,
                            realAmount_old: x.realAmount,
                            maxDiscountAmount: Number(maxDiscountAmount),
                            productQuantity_old: x.sendQty,
                            sendQty,
                            boxNum: boxNum,
                            stock_warning: x.sendProQty > x.stockUnit ? x.stockUnit + "(库存不足)" : x.stockUnit,
                            IsWarning: x.sendProQty > x.stockUnit ? 1 : 0,
                        };
                    });
                    for (let i = 0; i < this.goodsData.length; i++) {
                        if (this.goodsData[i].IsWarning == 1) {
                            this.skuStockWaring.push(this.goodsData[i].productName + "(库存不足)");
                        }
                    }
                    // 监听滚动条变化
                    this.$nextTick(() => {
                        const dom = this.$refs.table.$el.querySelectorAll('.ant-table-body')[0]
                        dom.addEventListener("scroll", () => {
                            this.$refs.table.$el.querySelectorAll('.ant-table-body')[1].scrollLeft = dom.scrollLeft
                        }, true)
                    })
                }
                if (res.code === 510) {
                    this.$message.warning(res.message);
                }
                this.loading = false;
            });
        },
        onChangeAmount(event, row) {
            row.realAmount = event;
        },
        /**
         * 总数 只
         * sendProQty 总只数
         * sendQty 箱数
         * */
        onChangeQuantity(event, row) {
            row.sendProQty = event;
            row.sendQty = fixedThree(event / row.productSkuSpec);
            this.countRowTotal(row)
        },
        // 箱数
        onChangeBox(event, row) {
            event = Math.floor(event)
            row.sendQty = event;
            row.sendProQty = event * row.productSkuSpec;
            this.countRowTotal(row)
        },
        /**
         * 计算库存数量
         * 计算5个折扣
         * 计算fixedDiscountAmount和优惠额度
         * 固定折扣额：（总金额-4大折扣）* 固定折扣率
         * 优惠金额：4大折扣 + 固定折扣额
         * */
        countRowTotal(row) {
            console.log(row)
            if (row.stockUnit < row.sendProQty) {
                row.stock_warning = row.stockUnit + "(库存不足)";
                this.pushSkuWaring(row.productName + "(库存不足)");
            } else {
                row.stock_warning = row.stockUnit;
                this.popSkuWaring(row.productName + "(库存不足)");
            }
            row.totalProductAmount = fixedTwo(row.sendProQty * row.minUnitPrice);
            row.maxDiscountAmount = fixedTwo(row.totalProductAmount * row.fourMaxRate / 100);

            // 4大折扣
            row.productDiscountAmount = fixedTwo(row.totalProductAmount * (row.productDiscountRate / 100))
            row.promotionDiscountAmount = fixedTwo(row.totalProductAmount * (row.promotionDiscountRate / 100))
            row.missionDiscountAmount = fixedTwo(row.totalProductAmount * (row.missionDiscountRate / 100))
            row.adjustDiscountAmount = fixedTwo(row.totalProductAmount * (row.adjustDiscountRate / 100))

            //  固定折扣额
            row.fixedDiscountAmount = fixedTwo((row.totalProductAmount - row.productDiscountAmount - row.promotionDiscountAmount - row.missionDiscountAmount - row.adjustDiscountAmount) * row.fixedDiscountRate / 100)

            this.setNeedPayAmountAndDiscountAmount(row);
        },
        /**
         * 最大数量不超过row.fourMaxRate
         * 输入折扣率后，就需要重新计算折扣和应付金额
         * 折扣金额不能大于购买物品的总金额,大于总金额时，重新记录折扣率,调整了折扣率，再次计算
         * */
        onChangeProductRate(event, row) {
            if (event > row.fourMaxRate) {
                event = row.fourMaxRate;
            }
            if (event < 0) {
                event = 0;
            }
            console.log(event);
            row.productDiscountRate = event;
            row.productDiscountAmount = fixedTwo(event * row.totalProductAmount / 100);
            this.countChangeDeal(row, 1)
        },
        /**
         *  货物优惠折扣额
         *  反算折扣率
        */
        onChangeProductAmount(event, row) {
            let max = row.maxDiscountAmount;
            if (event > max) {
                event = max;
            }
            if (event < 0) {
                event = 0;
            }
            row.productDiscountAmount = event;
            row.productDiscountRate = fixedTwo(event / row.totalProductAmount * 100);
            this.countChangeDeal(row, 1)
        },
        /**
         * 折扣统一处理计算
         * type ：不同折扣单独计算
         * 最大输入优惠： 4大折扣额度最大额
         * 重新计算固定折扣额度
         * 4大折扣 > 4大折扣最大值重新计算额度与比例
         */
        countChangeDeal(row, type) {
            let fourAmount = fixedTwo(row.productDiscountAmount + row.promotionDiscountAmount + row.missionDiscountAmount + row.adjustDiscountAmount)

            row.fixedDiscountAmount = fixedTwo((row.totalProductAmount - fourAmount) * row.fixedDiscountRate / 100)

            this.setNeedPayAmountAndDiscountAmount(row);

            const _maxDiscount = row.maxDiscountAmount
            console.log(_maxDiscount, fourAmount);
            if (fourAmount > _maxDiscount) {
                if (type == 1) {
                    let amount = _maxDiscount - (row.promotionDiscountAmount + row.missionDiscountAmount + row.adjustDiscountAmount)
                    amount = amount <= 0 ? 0 : amount;
                    row.productDiscountAmount = fixedTwo(amount);
                    let rate = fixedTwo(100 * row.productDiscountAmount / row.totalProductAmount);
                    row.productDiscountRate = fixedTwo(rate);
                } else if (type == 2) {
                    let amount = _maxDiscount - (row.productDiscountAmount + row.missionDiscountAmount + row.adjustDiscountAmount)
                    amount = amount <= 0 ? 0 : amount;
                    row.promotionDiscountAmount = fixedTwo(amount);
                    let rate = 100 * row.promotionDiscountAmount / row.totalProductAmount;
                    row.promotionDiscountRate = fixedTwo(rate);
                } else if (type == 3) {
                    let amount = _maxDiscount - (row.productDiscountAmount + row.promotionDiscountAmount + row.adjustDiscountAmount);
                    amount = amount <= 0 ? 0 : amount;
                    row.missionDiscountAmount = fixedTwo(amount);
                    let rate = 100 * row.missionDiscountAmount / row.totalProductAmount;
                    row.missionDiscountRate = fixedTwo(rate);
                } else if (type == 4) {
                    let amount = _maxDiscount - (row.productDiscountAmount + row.promotionDiscountAmount + row.missionDiscountAmount);
                    amount = amount <= 0 ? 0 : amount;
                    row.adjustDiscountAmount = fixedTwo(amount);
                    let rate = 100 * row.adjustDiscountAmount / row.totalProductAmount;
                    row.adjustDiscountRate = fixedTwo(rate);
                }
                row.fixedDiscountAmount = fixedTwo((row.totalProductAmount - row.productDiscountAmount - row.promotionDiscountAmount - row.missionDiscountAmount - row.adjustDiscountAmount) * row.fixedDiscountRate / 100)

                this.setNeedPayAmountAndDiscountAmount(row);
            }
        },

        /***
         * 促销费用折扣
         * 折扣金额不能大于购买物品的总金额，大于总金额时，重新记录折扣率，调整了折扣率，再次计算
         */
        onChangePromotionRate(event, row) {
            if (event > row.fourMaxRate) {
                event = row.fourMaxRate;
            }
            if (event < 0) {
                event = 0;
            }
            row.promotionDiscountRate = event;
            row.promotionDiscountAmount = fixedTwo(event * row.totalProductAmount / 100);
            this.countChangeDeal(row, 2)
        },
        // 这是特殊订单单品价格
        setPrice(event, row) {
            row.productPrice = fixedTwo(row.productSkuSpec * event);
            row.minUnitPrice = event;
            this.countRowTotal(row);
        },
        onChangePromotionAmount(event, row) {
            let max = row.maxDiscountAmount;
            if (event > max) {
                event = max;
            }
            if (event < 0) {
                event = 0;
            }
            row.promotionDiscountAmount = event;
            row.promotionDiscountRate = fixedTwo(event / row.totalProductAmount * 100);
            this.countChangeDeal(row, 2)
        },
        /**
         * 任务完成折扣额
         * 输入折扣率后，就需要重新计算折扣和应付金额
         */
        onChangeMissionRate(event, row) {
            if (event > row.fourMaxRate) {
                event = row.fourMaxRate;
            }
            if (event < 0) {
                event = 0;
            }
            row.missionDiscountRate = event;
            row.missionDiscountAmount = fixedTwo(event * row.totalProductAmount / 100);
            this.countChangeDeal(row, 3)
        },
        onChangeMissionAmount(event, row) {
            let max = row.maxDiscountAmount;
            if (event > max) {
                event = max;
            }
            if (event < 0) {
                event = 0;
            }
            row.missionDiscountAmount = event;
            row.missionDiscountRate = fixedTwo(event / row.totalProductAmount * 100);
            this.countChangeDeal(row, 3)
        },
        onChangeAdjustRate(event, row) {
            if (event > row.fourMaxRate) {
                event = row.fourMaxRate;
            }
            if (event < 0) {
                event = 0;
            }
            row.adjustDiscountRate = event;
            row.adjustDiscountAmount = fixedTwo(event * row.totalProductAmount / 100);
            this.countChangeDeal(row, 4)
        },
        onChangeAdjustAmount(event, row) {
            let max = row.maxDiscountAmount;
            if (event > max) {
                event = max;
            }
            if (event < 0) {
                event = 0;
            }
            row.adjustDiscountAmount = event;
            row.adjustDiscountRate = fixedTwo(event / row.totalProductAmount * 100);
            this.countChangeDeal(row, 4)
        },
        //重新计算折扣金额和应付金额
        setNeedPayAmountAndDiscountAmount(row) {
            row.discountAmount = fixedTwo(row.productDiscountAmount + row.promotionDiscountAmount + row.missionDiscountAmount + row.adjustDiscountAmount + row.fixedDiscountAmount);
            row.needPayAmount = fixedTwo(row.sendProQty * row.minUnitPrice - row.discountAmount);
        },
        close() {
            this.form.resetFields();
            this.$emit("close");
            this.visible = false;
        },
        /**
         * 提交表单
         * 根据orderFlag处理提交逻辑
         * 0: 拒绝 需填写拒绝备注
         * 1: 同意 验证其他条件
         */
        handleSubmit() {
            let formData = {
                status: this.model.orderFlag,
                note: '',
                orderId: this.model.id,
                itemMap: {},
            };
            if (this.model.orderFlag != 1) {
                formData.note = this.form.getFieldValue("note");
                this.form.validateFields((err, values) => {
                    if (!err) {
                        this.submitAudit(formData)
                    }
                });
            } else {
                let itemMap = {};
                const { productDiscountAmount,
                    promotionDiscountAmount,
                    missionDiscountAmount,
                    adjustDiscountAmount } = this.footerDataSource[0]

                if (this.discountData.promotionRemainAmount < promotionDiscountAmount
                    || this.discountData.productRemainAmount < productDiscountAmount
                    || this.discountData.missionRemainAmount < missionDiscountAmount
                    || this.discountData.adjustRemainAmount < adjustDiscountAmount) {
                    this.$message.error("已超过最大可用剩余折扣，请重新设置！");
                    return;
                }
                const ynNeedZero = this.goodsData.filter(x => x.needPayAmount < 0).length > 0;
                if (ynNeedZero) {
                    this.$message.error('应付金额<0,请重新确认!');
                    return;
                }

                this.goodsData.forEach((row) => {
                    const {
                        sendQty,
                        sendProQty,
                        realAmount,
                        productDiscountAmount,
                        promotionDiscountAmount,
                        missionDiscountAmount,
                        adjustDiscountAmount,
                        productDiscountRate,
                        promotionDiscountRate,
                        missionDiscountRate,
                        adjustDiscountRate,
                        needPayAmount,
                        id,
                        totalProductAmount,
                        fixedDiscountAmount,
                        fixedDiscountRate,
                        minUnitPrice
                    } = row;

                    itemMap[row.id] = {
                        sendQty,
                        sendProQty,
                        totalProductAmount,
                        realAmount,
                        productDiscountAmount,
                        promotionDiscountAmount,
                        missionDiscountAmount,
                        adjustDiscountAmount,
                        productDiscountRate,
                        promotionDiscountRate,
                        missionDiscountRate,
                        adjustDiscountRate,
                        fixedDiscountRate,
                        needPayAmount,
                        id,
                        fixedDiscountAmount,
                        minUnitPrice
                    };
                    // }
                });
                formData.itemMap = itemMap;
                this.submitAudit(formData);
            }

        },
        submitAudit(formData) {
            console.log(formData);
            this.confirmLoading = true;
            httpAction(this.url.approve, formData, "put")
                .then((res) => {
                    this.confirmLoading = false;
                    if (res.success) {
                        this.$message.success(res.message);
                        this.$emit("ok");
                        this.close();
                    } else {
                        this.$message.error(res.message);
                    }
                })
        },
        handleCancel() {
            this.close();
        },
        handleWarehouseFlag(e) {
            this.model.orderFlag = e;
            this.selectedStock = [];
            this.stockList = [];
        },
        /**
         * 获取当前经销商额度信息, 设置初始是否可编辑
         * 额度为0不可编辑
         * 货物优惠余额 productRemainAmount
         * 促销费用余额 promotionRemainAmount
         * 任务达成余额 missionRemainAmount
         * 调价补差余额 adjustRemainAmount
         */
        getStoreInfo(storeId) {
            let param = {};
            getAction(`${this.url.storeInfo }/${storeId}/${this.model.id}`, param).then(res => {
                if (res.success) {
                    this.creditLimit = res.result.creditLimit;
                    this.remainCreditLimit = res.result.remainCreditLimit;
                    this.usedCreditLimit = res.result.usedCreditLimit;

                    const { productRemainAmount, promotionRemainAmount, missionRemainAmount, adjustRemainAmount, balance } = res.result.dealerDiscount

                    this.discountData =
                    {
                        id: 1,
                        orderNo: this.model.orderNo,
                        balance,
                        productRemainAmount,
                        productRemainAmount_total: productRemainAmount,

                        promotionRemainAmount,
                        promotionRemainAmount_total: promotionRemainAmount,

                        missionRemainAmount,
                        missionRemainAmount_total: missionRemainAmount,

                        adjustRemainAmount,
                        adjustRemainAmount_total: adjustRemainAmount
                    }

                    this.disableMissionDiscountInput = !(missionRemainAmount > 0);
                    this.disableProductDiscountInput = !(productRemainAmount > 0);
                    this.disablePromotionDiscountInput = !(promotionRemainAmount > 0);
                    this.disableAdjustDiscountInput = !(adjustRemainAmount > 0);
                } else {
                    console.log(res.message)
                }
            })
        },
        pushSkuWaring(msg) {
            if (!this.skuStockWaring.includes(msg)) {
                this.skuStockWaring.push(msg);
            }
        },
        popSkuWaring(msg) {
            let index = this.skuStockWaring.indexOf(msg);
            if (index >= 0) {
                this.skuStockWaring.splice(index, 1)
            }
        },
        // 批量设置比率
        setRate(key) {
            const temp = this.goodsData[0]
            this.goodsData.forEach((x, i) => {
                if (i > 0) {
                    switch (key) {
                        case 'productDiscountRate':
                            this.onChangeProductRate(temp[key] || 0, x)
                            break;
                        case 'promotionDiscountRate':
                            this.onChangePromotionRate(temp[key] || 0, x)
                            break;
                        case 'missionDiscountRate':
                            this.onChangeMissionRate(temp[key] || 0, x)
                            break;
                        case 'adjustDiscountRate':
                            this.onChangeAdjustRate(temp[key] || 0, x)
                            break;
                        default:
                            break;
                    }
                }
            })
        },
        // 取消
        handleCancelOrder() {
            if (this.model.status === 1 || this.model.status === 0 || this.model.status === 6 || this.model.status === 7
                || this.model.status === 9 || this.model.status === 10) {
                    this.loadingC = true;
                httpAction(this.url.cancel, { id: this.model.id }, 'put').then((res) => {
                    this.loadingC = false;
                    if (res.success) {
                        this.$message.success(res.message);
                        this.visible = false;
                        setTimeout(() => {
                            this.$emit('ok');
                        }, 300)
                    } else {
                        this.$message.warning(res.message)
                    }
                })
            } else {
                this.$message.warning('订单：' + this.model.id + ' 当前已不可取消')
            }
        },
        // 删除
        handleRepeal() {
            this.loadingD = true;
            httpAction(this.url.repeal, { id: this.model.id }, 'put').then((res) => {
                this.loadingD = false;
                if (res.success) {
                    this.$message.success(res.message);
                    this.visible = false;
                    setTimeout(() => {
                        this.$emit('ok');
                    }, 300)
                } else {
                    this.$message.warning(res.message)
                }
            })
        },
    },
    components: {
        tableHead
    }
     
};
</script>
<style scoped lang="less">
/deep/ .ant-table {
    font-size: 12px;
}

.minTable {

    /deep/ .ant-table {
        th,
        td {
            padding-left: 2px !important;
            padding-right: 2px !important;
        }
    }

    /deep/ .ant-table-column-title {
        white-space: pre;
    }

    .red {
        color: red;
        font-weight: 600;
    }
}

/deep/ .ant-table-footer {
    padding: 0 !important;

}

.footerTable {

    /deep/ .ant-table-thead {
        display: none;
    }

    /deep/ .ant-table-body {
        overflow-x: hidden !important;
    }

}
#orderEditTable /deep/ tr>td,
#orderEditTable /deep/ td {
    padding: 0 !important;
    height: 1px;
}
.canDeal{
    height: 100%;
    background: #b3ffa4;
    padding: 2px 0;
}
</style>
